<template>
  <div class="app-container">
    <!-- <h3>处方管理</h3> -->
    <!-- 查询框 -->
    <div class="filter-container">
      <el-input
        v-model="pageParam.model.patient"
        style="width: 200px;"
        placeholder="姓名查询..."
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @input="handleFilter"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加处方
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="list" fit highlight-current-row style="width: 100%;" @sort-change="sortChange">

      <el-table-column class="filter-item" type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">

            <el-alert v-for="(item,index) in row.recipelChild" type="warning" :closable="false">
              <h2 align="center">药品{{ index+1 }}</h2>

              <div align="right">
                <el-button v-if="row.status==0" align="right" size="small" type="danger" @click="deleteChild(item.id)">
                  删除药品
                </el-button>
                <el-button v-else align="right" disabled size="small" type="danger" @click="deleteChild(item.id)">
                  删除药品
                </el-button>
              </div>

              <el-form-item label="药品名字">
                <span>{{ item.medicinalName }}</span>
              </el-form-item>

              <el-form-item label="数量">
                <span>{{ item.count }}</span>
              </el-form-item>

              <el-form-item label="建议用法">
                <span>{{ item.describe }}</span>
              </el-form-item>

              <el-form-item label="规格">
                <span>{{ item.standards }}</span>
              </el-form-item>

              <el-form-item label="功效">
                <span>{{ item.functions }}</span>
              </el-form-item>

              <hr>
            </el-alert>
          </el-form>
        </template>
      </el-table-column>

      <!-- 表格字段 -->
      <el-table-column type="index" label="序号"/>
      <el-table-column prop="doctor" label="开药医生"/>
      <el-table-column prop="patient" label="病人"/>
      <el-table-column prop="createTime" label="开药时间"/>

      <el-table-column label="操作" fit width="300px">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status==0" size="small" type="primary" @click="handleUpdate(row)">编辑</el-button>
          <el-button v-else size="small" disabled type="primary" @click="handleUpdate(row)">已核对</el-button>
          <el-button v-if="row.status==2" size="small" type="danger" @click="handleDrawbackMedicinal(row)">退药
          </el-button>
          <el-button v-if="row.status==3" size="small" disabled type="danger" @click="handleDrawbackMedicinal(row)">
            退药中
          </el-button>
          <el-button v-if="row.status==4" size="small" type="danger" @click="handleDrawbackMedicinal(row)">
            退药驳回
          </el-button>
          <el-button v-if="row.status==0" size="small" type="danger" @click="handleDelete(row,$index)"
                     v-permission="['admin']">删除
          </el-button>
          <el-button v-if="row.status==0" size="small" type="success" @click="handleMedicinalCreate(row.id)">
            添加药品
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getListByPage"
    />
    <!-- 弹窗组件 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >

        <!-- 弹窗(生成主处方) -->
        <el-form-item label="输入病人住院编号" prop="time">
          <el-input v-model="no"/>
          <el-button @click="getPatientByNo">
            查询
          </el-button>
          <span>{{ application == null ? "" : application.patientName }}</span>
        </el-form-item>

        <!--        <el-form-item label="开药医生" prop="doctor">-->
        <!--          <template>-->
        <!--            {{temp.doctor}}}-->
        <!--            <el-select v-model="temp.doctorId" placeholder="请选择医生">-->
        <!--              <el-option-->
        <!--                v-for="item in doctorList"-->
        <!--                :key="item.id"-->
        <!--                :label="item.realName"-->
        <!--                :value="item.id"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--          </template>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 弹窗组件 -->
    <el-dialog title="添加药方" :visible.sync="MedicinalVisible">
      <el-form
        ref="MedicinaldataForm"
        :rules="rules"
        :model="childtemp"
        label-position="right"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >

        <!-- 弹窗(添加药品) -->
        <el-form-item label="药品种类" prop="categoryId">
          <template>

            <el-select v-model="categoryId" placeholder="选择药品种类" @change="getMedicinal(categoryId)">
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.categroyName"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="选择药品" prop="medicinalId">
          <template>
            <el-select v-model="childtemp.medicinalId" placeholder="请选择药品">
              <el-option
                v-for="item in medicinalList"
                :key="item.id"
                :label="item.medicinalName"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="数量" prop="count">
          <el-input v-model="childtemp.count"/>
        </el-form-item>

        <el-form-item label="推荐用量" prop="describe">
          <el-input v-model="childtemp.describe"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="MedicinalVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createMedData(recipelId)">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel"/>
        <el-table-column prop="pv" label="Pv"/>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {getByNo} from '@/api/application/application'
  import {
    mapGetters,
    mapState
  } from 'vuex'

  import {
    getToken
  } from '@/utils/auth'

  import {
    drawbackMedicinal,
    searchSomeRecipelPage,
    insertOne,
    deleteOne,
    updateOne,
    selectOne
  } from '@/api/recipel/recipel'

  import {
    searchSomeChildPage,
    insertChild,
    deleteChild,
    updateChild,
    selectChild
  } from '@/api/recipel/recipel_child'

  import {
    selectPatientList
  } from '@/api/patient/patient'

  import {
    selectDoctorList
  } from '@/api/his_user/his_user'

  import {
    selectMedicinalBySuperId
  } from '@/api/medicinal/medicinal'

  import {
    searchCategroyList
  } from '@/api/medicinal/medicinalCategroy'

  // 导入组件  记得声明组件
  import Pagination from '@/components/Pagination'

  export default {
    components: { // 在这里声明组件
      Pagination
    },
    computed: {
      ...mapGetters({
        'categroyName': 'categroyName'
      }),
      editor() {
        return this.$refs.myQuillEditor.quill
      }
    },
    data() {
      return {
        dialogVisible: false,
        list: [], // 列表数据
        total: 0,
        application: '',
        no: '',
        listQuery: { // 分页 排序  查询参数
          pageNum: 1,
          pageSize: 5
        },
        fieldQuery: { // 按字段查询
          realName: ''
        },
        dialogFormVisible: false,
        MedicinalVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPvVisible: false,
        pvData: [],
        temp: {
          id: '',
          doctorId: '',
          patientId: '',
          createTime: '',
          isDelete: '',
          status: '',
          doctor: '',
          patient: '',
          recipelChild: []
        },
        childtemp: {
          id: '',
          recipelId: '',
          medicinalId: '',
          count: '',
          describe: '',
          createTime: '',
          isDelete: ''
        },
        tempImageList: [],
        newsCategoryList: [],
        rules: {},
        pageParam: {
          pageNum: 1,
          pageSize: 6,
          model: {patient: ''},
          orderParams: [],
          superSearchKeyWord: ''
        },
        categoryId: '',
        recipelId: '',
        roleList: [],
        doctorList: [],
        patientList: [],
        categoryList: [],
        medicinalList: []

      }
    },
    created() {
      this.getListByPage()
    },
    mounted() {
      this.getNewsCategoryList()
    },
    methods: {
      // 根据病人住院编号获取病人信息
      getPatientByNo() {
        getByNo(this.no).then(res => {
          //alert(JSON.stringify(res.content))
          this.temp.patientId = res.content.patientId
          this.application = res.content
        })
      },
      sortChange(val) {
        // console.log("排序参数",val)
        const prop = val.prop
        const order = val.order === 'ascending' ? 'asc' : 'desc'
        const orderParam = prop + ' ' + order
        // console.log(orderParam)
        for (let i = 0; i < this.pageParam.orderParams.length; i++) {
          if (this.pageParam.orderParams[i].indexOf(prop) > -1) {
            this.pageParam.orderParams.splice(i, 1)
          }
        }
        this.pageParam.orderParams.push(orderParam)
        console.log(this.pageParam.orderParams)
        this.getListByPage()
      },
      getNewsCategoryList() {
        const pageNum = 1
        const pageSize = 1000
        const orderParams = []
        const model = {
          checkStatus: 1 // 只查询 已经审核通过的分类
        }
        const pageParam = {
          pageNum,
          pageSize,
          orderParams,
          model
        }
      },
      getListByPage() {
        this.pageParam.pageNum = this.listQuery.pageNum
        this.pageParam.pageSize = this.listQuery.pageSize

        console.log(this.pageParam.orderParams)

        searchSomeRecipelPage(this.pageParam).then(res => {
          console.log('列表数据' + JSON.stringify(res.content.list.recipelChild))
          this.list = res.content.list
          this.total = res.content.total
        }).catch(err => {
          console.log(err)
        })
        selectDoctorList().then(res => {
          this.doctorList = res.content
        })
        selectPatientList().then(res => {
          this.patientList = res.content
        })
        searchCategroyList().then(res => {
          // console.log(res)
          this.categoryList = res.content
        })
      },
      getMedicinal(id) {
        selectMedicinalBySuperId(id).then(res => {
          this.medicinalList = res.content
        })
      },

      handleFilter() {
        this.listQuery.page = 1
        this.getListByPage()
      },
      handleCreate() {
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        this.getNewsCategoryList()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleMedicinalCreate(row) {
        console.log('Med:' + row)
        this.recipelId = row
        this.tempImageList = []
        // this.$refs.imagesUpload.clearFiles()
        this.resetTemp()
        // console.log(this.userName)
        this.temp.createUserNickName = this.storeNickName
        this.MedicinalVisible = true
        // this.$nextTick(() => {
        //   this.$refs['MedicinaldataForm'].clearValidate()
        // })
      },
      handleUpdate(row) {
        console.log('edit:' + row)
        this.temp = Object.assign({}, row) // copy obj
        this.temp.id = row.id
        this.dialogStatus = 'update'
        // this.getTempImageList() // 展示商品图片列表
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row, index) {
        const temp = {
          id: row.id
        }

        deleteOne(temp).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      deleteChild(id) {
        const temp = {
          id: id
        }
        deleteChild(temp).then((res) => {
          this.MedicinalVisible = false
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            insertOne(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateData() {
        this.$refs['MedicinaldataForm'].validate((valid) => {
          if (valid) {
            updateOne(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      createMedData(id) {
        this.$refs['MedicinaldataForm'].validate((valid) => {
          this.childtemp.recipelId = this.recipelId
          console.log(this.childtemp.id + '+++' + this.recipelId)
          if (valid) {
            insertChild(this.childtemp).then(() => {
              this.MedicinalVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      updateMedData() {
        this.$refs['MedicinaldataForm'].validate((valid) => {
          if (valid) {
            updateChild(this.childtemp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.getListByPage()
            })
          }
        })
      },
      handleDrawbackMedicinal(recipel) {
        drawbackMedicinal(recipel).then((res) => {
          this.$notify({
            title: '成功',
            message: '申请成功',
            type: 'success',
            duration: 2000
          })
          this.getListByPage()
        })
      },
      resetTemp() {
        this.temp = {
          id: '',
          doctorId: '',
          patientId: '',
          createTime: '',
          isDelete: '',
          status: '',
          doctor: '',
          patient: '',
          recipelChild: []
        }
      },

      resetMedTemp() {
        this.medtemp = {
          id: '',
          recipelId: '',
          medicinalId: '',
          count: '',
          describe: '',
          createTime: '',
          isDelete: ''
        }
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)

        const imageUrl = file.response == undefined ? file.url.replace('blob:', '') : file.response.content
        // let imageUrl = ''
        const productImageData = {
          imageUrl: imageUrl
        }
        deleteSomeProductimageTrueByCondition(productImageData).then(() => {
        })
      },
      onEditorBlur(quill) {
        // console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        // console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        // console.log('editor ready!', quill)
      },
      onEditorChange({
                       quill,
                       html,
                       text
                     }) {
        // console.log('editor change!', quill, html, text)
        this.temp.description = html
      },
      categoryChange() {
        this.getListByPage()
      }
    }
  }
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
